package com.shockweb.service;

import java.util.Random;

import com.shockweb.client.ClientException;
import com.shockweb.client.impl.RegisterClient;
import com.shockweb.common.log.LogManager;
import com.shockweb.service.config.ServiceConfig;

/**
 * 服务器管理类
 * 
 * @author 彭明华
 * 2018年1月10日 创建
 */
public class ServerManager {
	
	/**
	 * 连接到注册服务器客户端
	 */
	private RegisterClient register = null;
	
	/**
	 * 返回注册服务器客户端
	 * @return
	 */
	public RegisterClient getRegisterClient()throws ServiceServerException{
		if(register==null || !register.isActive()){
			nextRegisterClient();
		}
		return register;
	}
	/**
	 * 所有注册服务器地址
	 */
	private String[] registerServers = null;
	
	/**
	 * 设置注册服务器
	 * @param registerServers
	 */
	public void setRegisterServers(String[] registerServers){
		this.registerServers = registerServers;
	}
	
	/**
	 * 当前同步服务实例
	 */
	private static ServerManager instance = new ServerManager();
	
	/**
	 * 获取当前实例
	 * @return
	 */
	public static ServerManager getInstance(){
		return instance;
	}
	
	/**
	 * 配置文件
	 */
	private ServiceConfig config = null;
	
	/**
	 * 启动服务
	 * @param servers
	 */
	public static void init(ServiceConfig config)throws ServiceServerException {
		synchronized(instance){
			instance.config = config;
			if(config.getRegisterServerUrls()!=null){
				instance.registerServers = config.getRegisterServerUrls().split(",");
				instance.nextRegisterClient();
			}
		}
	}
	
	/**
	 * 获取下一个可用的RegisterClient
	 */
	public void nextRegisterClient()throws ServiceServerException{
		if(registerServers!=null){
			int index = new Random().nextInt(registerServers.length);
			register = new RegisterClient(config.getClientTimeOut(),config.getClientConnectTimeOut(),
	    			config.getClientSleepTime(),config.getClientIdleStateTime());
			int count = 0;
			while((register==null || !register.isActive()) && count<registerServers.length) {
				try{
					register.connect(registerServers[index]);
				} catch (ClientException e) {
					LogManager.warn(this.getClass(),"连接注册服务器失败 Server=" + registerServers[index]);
				}
				count ++;
				index ++;
				if(index>=registerServers.length){
					index -= registerServers.length;
				}
			}
		}
		if(register==null || !register.isActive()){
			throw new ServiceServerException("连接所有注册服务器异常");
		}
	}
	
	/**
	 * 关闭服务器管理类
	 */
	public static void close(){
		if(instance.register!=null){
			instance.register.close();
		}
	}
}
